package com.task;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.model.auto.SchoolIntroduction;
import com.model.auto.SchoolLabel;
import com.model.auto.SchoolV2;
import com.service.ISchoolIntroductionService;
import com.service.ISchoolLabelService;
import com.service.ISchoolV2Service;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 院校数据定时任务
 *
 * @author zhaoyifan
 * @date 2024/7/14 15:09
 */
@Service
@Slf4j
public class SchoolDataTask {

    @Autowired
    NamedParameterJdbcTemplate jdbcTemplate;
    @Autowired
    private ISchoolV2Service schoolService;
    @Autowired
    private ISchoolLabelService schoolLabelService;
    @Autowired
    private ISchoolIntroductionService schoolIntroductionService;

    @Scheduled(cron = "0 0 0/2 * * ?")
    public void syncSchoolInfo() {
        LambdaQueryWrapper<SchoolLabel> schoolLabelQuery = new LambdaQueryWrapper<SchoolLabel>()
                .isNotNull(SchoolLabel::getCode);
        List<SchoolLabel> schoolLabels = schoolLabelService.list(schoolLabelQuery);

        LambdaQueryWrapper<SchoolIntroduction> schoolIntroductionQuery = new LambdaQueryWrapper<SchoolIntroduction>()
                .isNotNull(SchoolIntroduction::getSchoolCode);
        List<SchoolIntroduction> introductions = schoolIntroductionService.list(schoolIntroductionQuery);


        List<SchoolV2> allData = new ArrayList<>();
        LambdaQueryWrapper<SchoolV2> queryBt = new LambdaQueryWrapper<SchoolV2>()
                .isNotNull(SchoolV2::getBatch).isNotNull(SchoolV2::getSchoolName)
                .isNotNull(SchoolV2::getCode).isNotNull(SchoolV2::getGroupProposedwc)
                .like(SchoolV2::getBatch,"普通批")
                .orderByAsc(SchoolV2::getGroupProposedwc);
        List<SchoolV2> dataBt = schoolService.list(queryBt);
        allData.addAll(dataBt);

        LambdaQueryWrapper<SchoolV2> queryTq = new LambdaQueryWrapper<SchoolV2>()
                .isNotNull(SchoolV2::getBatch).isNotNull(SchoolV2::getSchoolName)
                .isNotNull(SchoolV2::getCode).isNotNull(SchoolV2::getGroupProposedwc)
                .like(SchoolV2::getBatch,"提前批")
                .orderByAsc(SchoolV2::getGroupProposedwc);
        List<SchoolV2> dataTq = schoolService.list(queryTq);
        allData.addAll(dataTq);

        String sql = "INSERT INTO school_info_v2(`sort`, `school_name`, `code`, `city`, `province`, `level`, `major_plan`, `manager`, `school_type`, `logo`, `image`, `school_address`," +
                " `college_level`, `qualifications`, `nature`, `school_sort`, `school_sort_json`) " +
                "VALUES(:sort, :schoolName, :code, :city, :province, :level, :majorPlan, :manager, :schoolType, :logo, :image, :schoolAddress, :collegeLevel, :qualifications, :nature, :schoolSort, :schoolSortJson) " +
                "ON DUPLICATE KEY UPDATE `sort` = :sort, `city` = :city, `province` = :province, `level` = :level, major_plan = :majorPlan, manager = :manager, school_type = :schoolType, logo = :logo, image = :image, school_address = :schoolAddress," +
                " college_level = :collegeLevel, qualifications = :qualifications, nature = :nature, school_sort = :schoolSort, school_sort_json = :schoolSortJson";
        List<Map<String, Object>> params = new ArrayList<>();

        Map<String, String> schoolNameMap = new HashMap<>();
        for (SchoolV2 schoolV2 : allData) {
            if (schoolV2.getSchoolName().indexOf("合办") > 0) {
                continue;
            }
            if (Objects.nonNull(schoolNameMap.get(schoolV2.getSchoolName()))) {
                continue;
            }
            //获取院校介绍相关
            List<SchoolIntroduction> introductionList = introductions.stream().filter(introduction -> introduction.getSchoolName().equals(schoolV2.getSchoolName())).collect(Collectors.toList());
            if(CollectionUtils.isEmpty(introductionList)){
                continue;
            }

            schoolNameMap.put(schoolV2.getSchoolName(), "true");

            Map<String, Object> param = new HashMap<>(2);
            param.put("sort", schoolV2.getSort());
            param.put("schoolName", schoolV2.getSchoolName());
            param.put("code", schoolV2.getCode());
            param.put("city", schoolV2.getCity());
            param.put("level", schoolV2.getLevel());
            param.put("majorPlan", schoolV2.getMajorPlan());
            param.put("manager", schoolV2.getManager());
            param.put("schoolType", schoolV2.getSchoolType());

            if (Objects.nonNull(introductionList) && introductionList.size() > 0) {
                param.put("logo", introductionList.get(0).getLogo());
                param.put("image", introductionList.get(0).getImage());
                param.put("schoolAddress", introductionList.get(0).getSchoolAddress());
            } else {
                param.put("logo", "");
                param.put("image", "");
                param.put("schoolAddress", "");
            }
            //获取院校标签相关
            List<SchoolLabel> labelList = schoolLabels.stream().filter(schoolLabel -> schoolLabel.getName().equals(schoolV2.getSchoolName())).collect(Collectors.toList());
            if (Objects.nonNull(labelList) && labelList.size() > 0) {
                param.put("collegeLevel", getCollegeLevel(labelList.get(0).getCollegeLevel()));
                param.put("qualifications", getQualifications(labelList.get(0).getQualifications()));
                param.put("nature", getNature(labelList.get(0).getNature()));
                param.put("province", labelList.get(0).getCity());
                param.put("schoolSort", labelList.get(0).getSchoolSort());
                param.put("schoolSortJson", labelList.get(0).getSchoolSortJson());
            } else {
                param.put("collegeLevel", "");
                param.put("qualifications", "");
                param.put("nature", "");
                param.put("province", "");
                param.put("schoolSort", "");
                param.put("schoolSortJson", "");
            }
            params.add(param);
        }
        Map<String, Object>[] batchData = new Map[params.size()];
        int i = 0;
        for (Map<String, Object> param : params) {
            batchData[i] = param;
            i++;
        }
        jdbcTemplate.batchUpdate(sql, batchData);
        log.info("同步完成");
    }

    /**
     * 获取院校层级
     *
     * @param collegeLevel
     * @return
     */
    private String getCollegeLevel(String collegeLevel) {
        if (StringUtils.hasText(collegeLevel)) {
            List<String> returnList = new ArrayList<>();

            Map<String, String> collegeLevelMap = new HashMap<>();
            collegeLevelMap.put("1", "双一流");
            collegeLevelMap.put("2", "中央直管");
            collegeLevelMap.put("3", "985");
            collegeLevelMap.put("4", "211");
            collegeLevelMap.put("5", "双高计划");
            collegeLevelMap.put("6", "国家示范(骨干)");

            List<String> collegeLevelList = Arrays.asList(collegeLevel.split(","));
            for (String collegeLevelStr : collegeLevelList) {
                returnList.add(collegeLevelMap.get(collegeLevelStr));
            }

            return String.join(",", returnList);
        }
        return "";
    }

    /**
     * 获取博硕资格
     *
     * @param qualifications
     * @return
     */
    private String getQualifications(String qualifications) {
        if (StringUtils.hasText(qualifications)) {
            List<String> returnList = new ArrayList<>();

            Map<String, String> qualificationsMap = new HashMap<>();
            qualificationsMap.put("1", "硕士点");
            qualificationsMap.put("2", "博士点");
            qualificationsMap.put("3", "研究生院");
            qualificationsMap.put("4", "自划线");
            qualificationsMap.put("5", "推免资格");

            List<String> qualificationsList = Arrays.asList(qualifications.split(","));
            for (String qualificationsStr : qualificationsList) {
                returnList.add(qualificationsMap.get(qualificationsStr));
            }

            return String.join(",", returnList);
        }
        return "";
    }

    /**
     * 获取办学属性
     *
     * @param nature
     * @return
     */
    private String getNature(String nature) {
        if (StringUtils.hasText(nature)) {
            List<String> returnList = new ArrayList<>();

            Map<String, String> natureMap = new HashMap<>();
            natureMap.put("1", "公办");
            natureMap.put("2", "民办");
            natureMap.put("3", "合办");

            List<String> natureList = Arrays.asList(nature.split(","));
            for (String qualificationsStr : natureList) {
                returnList.add(natureMap.get(qualificationsStr));
            }

            return String.join(",", returnList);
        }
        return "";
    }
//
//    @Scheduled(cron = "0 0/2 * * * ?")
//    public void updateSchoolLabel() {
//        LambdaQueryWrapper<SchoolLabel> schoolLabelQuery = new LambdaQueryWrapper<SchoolLabel>()
//                .isNotNull(SchoolLabel::getCode);
//        List<SchoolLabel> schoolLabels = schoolLabelService.list(schoolLabelQuery);
//
//        for (SchoolLabel schoolLabel : schoolLabels) {
//            if (StringUtils.hasText(schoolLabel.getSchoolSort())) {
//                JSONObject aaa = new JSONObject();
//                List<String> aList = Arrays.asList(schoolLabel.getSchoolSort().split(" "));
//                for (int i = 0; i < aList.size(); i++) {
//                    if ("武书连".equals(aList.get(i)) || "校友会".equals(aList.get(i)) || "软科".equals(aList.get(i)) || "易度".equals(aList.get(i))) {
//                        aaa.put(aList.get(i), aList.get(i + 1));
//                    }
//                }
//                if(aaa.size()>1){
//                    schoolLabel.setSchoolSort(aaa.toJSONString());
//                    schoolLabelService.updateById(schoolLabel);
//                }
//            }
//        }
//    }
}
